<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\model\Admin;
use app\model\Route;
use app\model\Website;
use app\model\WebsiteLang;
use app\model\WebsiteSetting;
use app\service\CacheService;
use app\service\SitemapService;
use app\service\WebsiteLangService;
use app\validate\WebsiteValidate;
use app\service\WebsiteService;
use think\facade\Db;
use think\exception\ValidateException;
use think\facade\Lang;


class WebsiteController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function index(Website $website): \think\response\Json
    {
        $where = [
            ['seller_id','=',  $this->admin['seller_id']],
        ];
        $uid = $this -> admin['uid'];
        $authSiteId = [];
        if($uid != 1){
            $admin = new Admin();
            $adminInfo = $admin -> getAdmin(['seller_id' => $this->admin['seller_id'],'id' => $uid],['role.website'])['data'] -> toArray();
            $authSite = array_column($adminInfo['role'],'website');
            foreach($authSite as $val){
                $authSiteId = array_merge($authSiteId,array_column($val,'id'));
            }
            $authSiteId = array_unique($authSiteId);
            $where[] = ['id','in',$authSiteId];
        }
        $websiteList = $website->getAllCustomArrayData($where)['data'];
        $websiteList = makeTree($websiteList);
        return jsonReturn(0,Lang::get('成功'),$websiteList);
    }

    /**
     * 保存新建的资源
     *
     * @return \think\Response
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function save(Website $website): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            // 数据验证
            try{
                validate(WebsiteValidate::class)->scene('save')->check($param);
            }catch(ValidateException $e){
                return jsonReturn(-1, $e->getError());
            }
            $website->saveUnique(['seller_id'=>$this->admin['seller_id'],'title'=>$param['title']],'网站名称已存在');
            $param['seller_id'] = $this->admin['seller_id'];
            $param['status'] = 1;
            Db::startTrans();
            try{
                // 1. 保存站点到数据库
                $res = $website -> addWebsite($param);
                if($param['parent_id'] == 0){
                    $this->selfData($res['data'],$param['domain'],$param['parent_id']);
                }else{
                    $this->sonData($res['data'],$param['domain'],$param['parent_id']);
                }
                CacheService::deleteRelationCacheByObject($website);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                return jsonReturn(-5,$e->getMessage());
            }
            return json($res);
        }
        return jsonReturn(-3,Lang::get('请求方法错误'));
    }


    /**
     * @throws \app\exception\ModelException
     */
    public function selfData($siteId, $domain, $parentId)
    {
        // 2. 生成一份默认的站点配置，配置的值为空
        $tmpData = config('system.website_setting');
        $sysData = [
            "setting"=> json_encode($tmpData),
            "website_id"=>$siteId,
            "lang"=>config('lang.default_lang')
        ];
        $siteSetting = new WebsiteSetting();
        $siteSetting -> addWebsiteSetting($sysData);
        // 3. 选择站点语言简体中文，服务器为本地服务器
        $langData[]= [
            'seller_id' => $this->admin['seller_id'],
            'website_id'    => $siteId,
            'lang_name' => '简体中文',
            'lang' => config('lang.default_lang'),
        ];
        $WebsiteLang = new WebsiteLang();
        $WebsiteLang->addWebsiteLang($langData);
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    public function sonData($siteId, $domain, $parentId)
    {
        $website = new Website();
        // 1. 写入父站点的路由
        $parent = $website -> getWebsite(['id'=>$parentId,'seller_id'=>$this->admin['seller_id']])['data'];
        $parentDomain = $parent['domain'];
        $start = $parentId . '_' ;
        $path = CMS_ROOT . 'route';
        $files = glob("$path/$start*.php");
        foreach ($files as $file){
            $tmpStr = str_replace($parentDomain,$domain,file_get_contents($file));
            $basename = str_replace($start,$siteId.'_',basename($file));
            file_put_contents($path . DIRECTORY_SEPARATOR . $basename,$tmpStr);
        }
        // 父站点路由copy一份到子站点保存到数据库
        $route = new Route();
        $routes = $route -> getAllCustomArrayData(['seller_id'=>$this->admin['seller_id'],'website_id'=>$parentId])['data'];
        foreach ($routes as &$val){
            $val['website_id'] = $siteId;
            $val['seller_id'] = $this->admin['seller_id'];
            unset($val['id']);
            unset($val['create_time']);
            unset($val['update_time']);
        }
        unset($val);
        $route->addAllCustomData($routes);
        // 2. 写入语言+配置
        $WebsiteLang = new WebsiteLang();
        $parentLang = $WebsiteLang->getAllCustomArrayData(['id'=>$parentId,'seller_id'=>$this->admin['seller_id']])['data'];
        $lang = array_column($parentLang,'lang');
        $websiteLangService = new WebsiteLangService();
        $websiteLangService->setSiteLang(['seller_id'=>$this->admin['seller_id'],'site_id'=>$siteId,'lang'=>$lang]);
    }

    /**
     * 显示指定的资源
     *
     * @return \think\Response
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function read(Website $website): \think\response\Json
    {
        $id = (int)input('id');
        if(!$id){
            return jsonReturn(-1,Lang::get('网站ID不能为空'));
        }
        $where = [
            'id' => $id,
            'seller_id' => $this->admin['seller_id']
        ];
        $res = $website->getWebsite($where);
        return json($res);

    }

    /**
     * 设置网站状态
     * @param Website $website
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     */
    public function setStatus(Website $website)
    {
        if(!request()->isPost()){
            return jsonReturn(-3,Lang::get('请求方法错误'));
        }
        $param = $this->request->only(['id' => 0, 'status' => 1]);

        try {
            validate(WebsiteValidate::class)->scene('setStatus')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $where = [
            'id' => $param['id'],
            'seller_id' => $this->admin['seller_id'],
        ];

        if ($param['status'] == 2) {
            $childWhere = [
                'parent_id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
            ];
            $website->updateWebsite($childWhere, ['status' => $param['status']]);
        }
        $res = $website->updateWebsite($where, ['status' => $param['status']]);
        return json($res);
    }

    /**
     * 保存更新的资源
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     * @throws \ReflectionException
     */
    public function update(Website $website): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(WebsiteValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
            ];
            $site =  $website->getWebsite($where)['data'];
            if($param['domain'] != $site['domain']){
                // 修改路由域名配置
                $routePath = app()->getRootPath() . 'route'. DIRECTORY_SEPARATOR;
                $fileArr = hcScanDir($routePath.'*');
                foreach($fileArr as $val){
                    $siteId = $param['id'];
                    $pattern = '/^'.$siteId.'_/';
                    if(is_file($routePath . $val) && preg_match($pattern,$val)){
                        $conArr =  str_replace($site['domain'],$param['domain'],file_get_contents($routePath.$val));
                        file_put_contents($routePath.$val,$conArr);
                    }
                }
            }
            $res = $website -> updateWebsite($where,$param);
            CacheService::deleteRelationCacheByObject($website);
            return json($res);
        }
        return jsonReturn(-3,Lang::get('请求方法错误'));
    }

    /**
     * 删除指定资源
     *
     */
    public function delete(WebsiteService $websiteService): \think\response\Json
    {
        if(request()->isPost()){
            $id = (int)input('id');
            if(!$id){
                return jsonReturn(-1,Lang::get('网站ID不能为空'));
            }

            $res = $websiteService->deleteSite($id,$this->admin['seller_id']);

            return json($res);
        }
        return jsonReturn(-3,Lang::get('请求方法错误'));
    }

    /**
     * xml文件
     * @param SitemapService $sitemapService
     * @return \think\response\Json
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    public function sitemap(SitemapService $sitemapService): \think\response\Json
    {
        $siteId = (int)$this->request->param('website_id');
        $sellerId  = $this->admin['seller_id'];
        $res =  $sitemapService -> makeSitemap($siteId,$sellerId);
        return json($res);
    }
}
